package net.kazed.nextaction.tools;

import java.text.DateFormat;
import java.text.SimpleDateFormat;

import net.kazed.android.inject.Autowired;
import net.kazed.android.inject.InjectedActivity;
import net.kazed.nextaction.R;
import net.kazed.nextaction.database.backup.BackupService;
import net.kazed.nextaction.database.backup.ExportFileExistsException;
import net.kazed.nextaction.database.serialize.BackupFileSummary;
import net.kazed.nextaction.database.serialize.BackupFileSummaryQuery;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Display information of backup file.
 */
public class BackupItemActivity extends InjectedActivity {

   private static final int BACKUP_DELETE = Menu.FIRST;
   private static final int BACKUP_EXPORT = BACKUP_DELETE + 1;

   private static final String TAG = "BackupItemActivity";

   private BackupService backupService;
   
   private TextView fieldCreateDate;
   private TextView fieldNumberOfContexts;
   private TextView fieldNumberOfTasks;
   private Button mergeButton;
   private Button replaceButton;

   private Uri backupUri;
   private long backupId;

   @Autowired
   public void setBackupService(BackupService backupService) {
      this.backupService = backupService;
   }

   @Override
   public void onCreate(Bundle icicle) {
      super.onCreate(icicle);
      setContentView(R.layout.backup_item_view);
      setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);

      fieldCreateDate = (TextView) findViewById(R.id.create_date);
      fieldNumberOfContexts = (TextView) findViewById(R.id.number_of_contexts);
      fieldNumberOfTasks = (TextView) findViewById(R.id.number_of_tasks);

      mergeButton = (Button) findViewById(R.id.merge_button);
      mergeButton.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(BackupItemActivity.this);
            builder.setTitle(R.string.backup_merge_alert_title).setMessage(R.string.backup_merge_alert_message).setIcon(
                  android.R.drawable.ic_dialog_alert);
            builder.setPositiveButton(R.string.alert_yes, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int whichButton) {
                  restoreBackup("merge");
               }
            });
            builder.setNegativeButton(R.string.alert_no, null);
            builder.show();
         }
      });

      replaceButton = (Button) findViewById(R.id.replace_button);
      replaceButton.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(BackupItemActivity.this);
            builder.setTitle(R.string.backup_replace_alert_title).setMessage(R.string.backup_replace_alert_message).setIcon(
                  android.R.drawable.ic_dialog_alert);
            builder.setPositiveButton(R.string.alert_yes, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int whichButton) {
                  restoreBackup("replace");
               }
            });
            builder.setNegativeButton(R.string.alert_no, null);
            builder.show();
         }
      });

      backupUri = getIntent().getData();
      backupId = Long.parseLong(backupUri.getLastPathSegment());

      Intent returnIntent = new Intent();
      setResult(RESULT_OK, returnIntent);
   }

   @Override
   protected void onResume() {
      super.onResume();

      Cursor cursor = null;
      try {
         Uri summaryUri = ContentUris.withAppendedId(BackupFileSummary.CONTENT_ITEM_URI, backupId);
         cursor = managedQuery(summaryUri, null, null, null, null);
         BackupFileSummaryQuery query = new BackupFileSummaryQuery(cursor);
         BackupFileSummary summary = query.getBackupFileSummary();
         DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
         fieldCreateDate.setText(dateFormat.format(summary.getCreateDate()));
         fieldNumberOfContexts.setText(Integer.toString(summary.getNumberOfContexts()));
         fieldNumberOfTasks.setText(Integer.toString(summary.getNumberOfTasks()));
      } finally {
         if (cursor != null) {
            cursor.close();
         }
      }
   }

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      Resources resources = getResources();
      if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
         menu.add(0, BACKUP_EXPORT, 0, resources.getString(R.string.menu_export_backup)).setIcon(
               android.R.drawable.ic_menu_save).setAlphabeticShortcut('e');
      }
      MenuItem item = menu.add(0, BACKUP_DELETE, 0, resources.getString(R.string.menu_delete_backup)).setIcon(
            android.R.drawable.ic_menu_delete);
      item.setAlphabeticShortcut('d');
      return super.onCreateOptionsMenu(menu);
   }

   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
      switch (item.getItemId()) {
      case BACKUP_DELETE:
         AlertDialog.Builder builder = new AlertDialog.Builder(BackupItemActivity.this);
         builder.setTitle(R.string.backup_delete_alert_title).setMessage(R.string.backup_delete_alert_message).setIcon(
               android.R.drawable.ic_dialog_alert);
         builder.setPositiveButton(R.string.alert_yes, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
               backupService.delete(backupId);
               finish();
            }
         });
         builder.setNegativeButton(R.string.alert_no, null);
         builder.show();
         break;
      case BACKUP_EXPORT:
         try {
            backupService.copyToSdCard(backupId);
            Toast toast = Toast.makeText(BackupItemActivity.this, R.string.backup_export_successful, Toast.LENGTH_LONG);
            toast.show();
         } catch (ExportFileExistsException e) {
            Toast.makeText(BackupItemActivity.this, R.string.backup_export_exists_failure, Toast.LENGTH_LONG).show();
         } catch (RuntimeException e) {
            Log.e(TAG, "export failed", e);
            Toast.makeText(BackupItemActivity.this, R.string.backup_export_failure, Toast.LENGTH_LONG).show();
         }
         break;
      }
      return super.onOptionsItemSelected(item);
   }

   private void restoreBackup(final String type) {
      BusyDialog busyDialog = new BusyDialog(this, new BusyDialog.BackgroundAction() {
         public void execute() {
            if ("merge".equals(type)) {
               backupService.restoreMerge(backupId);
            } else {
               backupService.restoreReplace(backupId);
            }
         }
      }, new BusyDialog.DoneAction() {
         public void execute(Exception e) {
            if (e == null) {
               Toast toast = Toast.makeText(BackupItemActivity.this, R.string.backup_restore_successful, Toast.LENGTH_LONG);
               toast.show();
               finish();
            } else {
               Log.e(TAG, "import failed", e);
               Toast toast = Toast.makeText(BackupItemActivity.this, R.string.backup_restore_failure, Toast.LENGTH_LONG);
               toast.show();
            }
         }
      });
      busyDialog.execute(R.string.backup_restore_busy_title, R.string.backup_restore_busy_message);
   }

}